package com.example.serverSide.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.serverSide.mapper.*;
import com.example.serverSide.pojo.*;
import com.example.serverSide.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    OrdersHistoryMapper ordersHistoryMapper;
    @Autowired
    SysDeptMapper sysDeptMapper;
    @Autowired
    OrdersBoardMapper ordersBoardMapper;
    @Autowired
    OrdersHardwareMapper ordersHardwareMapper;

    @Override
    public void transferOrder(Orders orders) {
        Integer originStatus = orders.getStatus();
        orders.setStatus(originStatus+1);
        orders.setUpdateDate(null);
        OrdersHistory ordersHistory = new OrdersHistory();
        if (originStatus==1){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("等待设计师填写信息");
            ordersHistory.setBrief("流程转交设计师");
        }else if (originStatus==2){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("等待总经理/经理审批");
            ordersHistory.setBrief("流程转交经理审批");
        }else if (originStatus==5){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("等待安装师填写安装单");
            ordersHistory.setBrief("流程转交安装师");
        }else if (originStatus==6){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("等待财务确认收取结余费用");
            ordersHistory.setBrief("流程转交财务");
        }
        else if (originStatus==7){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("等待尾款收取确认");
            ordersHistory.setBrief("尾款信息提交, 等待尾款确认");
        }
        else if (originStatus==8){
            orders.setUpdater(orders.getUser());
            orders.setStatusInfo("订单完成");
            ordersHistory.setBrief("确认订单完成");
            orders.setStatus(0);
        }
        ordersMapper.updateById(orders);
        SysUser sysUser = sysUserMapper.selectById(orders.getUser());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setOperator(orders.getUsername()+"("+name+")");
        ordersHistory.setOrderId(orders.getId());
        ordersHistory.setOperate(0);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,ordersHistory.getOrderId())
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate())
                .eq(OrdersHistory::getBrief, ordersHistory.getBrief());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
    }

    @Override
    public String deleteOrder(String id) {
        ordersMapper.deleteById(id);
        LambdaQueryWrapper<OrdersHistory> history = new LambdaQueryWrapper<>();
        history.eq(OrdersHistory::getOrderId,id);
        ordersHistoryMapper.delete(history);
        return "success!";
    }

    @Override
    public String addOrder(Orders orders) {
        String utcTime = orders.getDealTimeD().toString();
        String originalDate  = orders.getDealDateD().toString();
        orders.setDealTime(orders.getDealTimeD().toString());
        orders.setDealDate(orders.getDealDateD().toString());
        System.out.println(utcTime+" "+originalDate);
        Orders orders1 = ordersMapper.selectById(orders.getId());
        orders.setCreator(orders.getSeller());
        orders.setUpdater(orders.getSeller());
        if (orders1 == null) {
            ordersMapper.insert(orders);
        }else {
            orders.setUpdateDate(null);
            ordersMapper.updateById(orders);
        }
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getUser());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("订单内容修改");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(orders.getId());
        ordersHistory.setOperate(1);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,ordersHistory.getOrderId())
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
        /*// 将字符串解析为Instant对象
        Instant instant = Instant.parse(utcTime);


        // 将Instant对象转换为北京时间的ZonedDateTime对象
        ZonedDateTime beijingDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));

        // 将ZonedDateTime对象格式化为字符串形式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String beijingTime = beijingDateTime.format(formatter);
        orders.setDealTime(beijingTime);
        //----------------------------------------------------------------
        String originalDate  = orders.getDealDate();
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy/MM/dd");
        *//*try {
            orders.setDealDate(targetFormat.format(originalFormat.parse(originalDate)));
        } catch (ParseException e) {
            e.printStackTrace();
        }*//*
        try {
            // 将原始日期字符串解析为 Date 对象
            Date date = originalFormat.parse(originalDate);

            // 将 Date 对象格式化为目标格式的字符串
            String formattedDate = targetFormat.format(date);
            orders.setDealDate(formattedDate);
            System.out.println("原始日期字符串: " + originalDate);
            System.out.println("转换后的日期字符串: " + formattedDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Orders orders1 = orderMapper.selectById(orders.getId());
        if (orders1 == null) {
            orderMapper.insert(orders);
        }else {
            orderMapper.updateById(orders);
        }
*/

        return "shit";
    }

    @Override
    public List<Orders> getOrders() {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>();
        List<Orders> orders = ordersMapper.selectList(queryWrapper);
        for (Orders order : orders) {
            String dealTime = order.getDealTime();
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0800"));
            //order.setDealTime(order.getDealTime());
            Long userId = order.getSeller();
            Long orderId = order.getId();
            SysUser sysUser = sysUserMapper.selectById(userId);
            SysUser generalManager1 = sysUserMapper.selectById(order.getGeneralManager1());
            SysUser generalManager2 = sysUserMapper.selectById(order.getGeneralManager2());

            LambdaQueryWrapper<OrdersHistory> orderHistoryQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
            orderHistoryQueryWrapper.eq(OrdersHistory::getOrderId, orderId);
            LambdaQueryWrapper<OrdersBoard> orderBoardQueryWrapper = new LambdaQueryWrapper<OrdersBoard>();
            orderBoardQueryWrapper.eq(OrdersBoard::getOrderId, orderId);
            LambdaQueryWrapper<OrdersHardware> orderHardwareQueryWrapper = new LambdaQueryWrapper<OrdersHardware>();
            orderHardwareQueryWrapper.eq(OrdersHardware::getOrderId, orderId);

            List<OrdersHistory> orderHistories = ordersHistoryMapper.selectList(orderHistoryQueryWrapper);
            List<OrdersBoard> ordersBoards = ordersBoardMapper.selectList(orderBoardQueryWrapper);
            List<OrdersHardware> ordersHardware = ordersHardwareMapper.selectList(orderHardwareQueryWrapper);
            if(generalManager1!=null) {
                order.setGeneralManager1Name(generalManager1.getRealName());
            }
            if(generalManager2!=null) {
                order.setGeneralManager2Name(generalManager2.getRealName());
            }
            order.setOrderHistories(orderHistories);
            order.setOrdersBoards(ordersBoards);
            order.setOrdersHardware(ordersHardware);
            order.setSellerName(sysUser.getRealName());
        }
        return orders;
    }

    @Override
    public Orders getOrder(Long id) {
        Orders order = ordersMapper.selectById(id);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0800"));
        Long userId = order.getSeller();
        Long orderId = order.getId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        SysUser generalManager1 = sysUserMapper.selectById(order.getGeneralManager1());
        SysUser generalManager2 = sysUserMapper.selectById(order.getGeneralManager2());
        LambdaQueryWrapper<OrdersHistory> orderHistoryQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        orderHistoryQueryWrapper.eq(OrdersHistory::getOrderId, orderId);
        LambdaQueryWrapper<OrdersBoard> orderBoardQueryWrapper = new LambdaQueryWrapper<OrdersBoard>();
        orderBoardQueryWrapper.eq(OrdersBoard::getOrderId, orderId);
        LambdaQueryWrapper<OrdersHardware> orderHardwareQueryWrapper = new LambdaQueryWrapper<OrdersHardware>();
        orderHardwareQueryWrapper.eq(OrdersHardware::getOrderId, orderId);
        List<OrdersHistory> orderHistories = ordersHistoryMapper.selectList(orderHistoryQueryWrapper);
        List<OrdersBoard> ordersBoards = ordersBoardMapper.selectList(orderBoardQueryWrapper);
        List<OrdersHardware> ordersHardware = ordersHardwareMapper.selectList(orderHardwareQueryWrapper);
        if(generalManager1!=null) {
            order.setGeneralManager1Name(generalManager1.getRealName());
        }
        if(generalManager2!=null) {
            order.setGeneralManager2Name(generalManager2.getRealName());
        }
        order.setOrderHistories(orderHistories);
        order.setOrdersBoards(ordersBoards);
        order.setOrdersHardware(ordersHardware);
        order.setSellerName(sysUser.getRealName());
        return order;
    }

    @Override
    public void updateOrderMaterial(Orders orders) {
        Long id = orders.getId();
        //板子
        List<OrdersBoard> ordersBoards = orders.getOrdersBoards();
        LambdaQueryWrapper<OrdersBoard> ordersBoardLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersBoardLambdaQueryWrapper.eq(OrdersBoard::getOrderId,id);
        ordersBoardMapper.delete(ordersBoardLambdaQueryWrapper);
        if(ordersBoards.size() > 0) {
            for (OrdersBoard ordersBoard: ordersBoards) {
                ordersBoard.setOrderId(id);
                ordersBoard.setBoardTitle("板子: "+ordersBoard.getBoardType()+" "+ordersBoard.getBoardBase()+" "+ordersBoard.getBoardColor());
                ordersBoardMapper.insert(ordersBoard);
            }
        }
        //五金
        List<OrdersHardware> ordersHardware = orders.getOrdersHardware();
        LambdaQueryWrapper<OrdersHardware> ordersHardwareLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersHardwareLambdaQueryWrapper.eq(OrdersHardware::getOrderId,id);
        ordersHardwareMapper.delete(ordersHardwareLambdaQueryWrapper);
        for (OrdersHardware hardware: ordersHardware) {
            hardware.setOrderId(id);
            ordersHardwareMapper.insert(hardware);
        }
        //订单
        orders.setUpdateDate(null);
        ordersMapper.updateById(orders);
        //历史
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getDesigner());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("订单材料内容修改");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(id);
        ordersHistory.setOperate(1);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,id)
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate())
                .eq(OrdersHistory::getBrief, ordersHistory.getBrief());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
    }

    @Override
    public void denyOrder(Orders orders) {
        Long id = orders.getId();
        Integer status = orders.getStatus();
        if(status == 3){
            orders.setGeneralManager1(orders.getUser());
            orders.setGeneralManager1Op("审批意见: 拒绝");
        }if(status == 4){
            orders.setGeneralManager2(orders.getUser());
            orders.setGeneralManager2Op("审批意见: 拒绝");
        }
        orders.setStatus(-1).setStatusInfo("订单审批未通过").setUpdater(null).setUpdateDate(null);
        /*Orders old = ordersMapper.selectById(orders.getId());
        orders.setGeneralManager1(old.getGeneralManager1());*/
        ordersMapper.updateById(orders);
        //历史
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getUser());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("订单审批意见：未通过");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(id);
        ordersHistory.setOperate(1);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,id)
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate())
                .eq(OrdersHistory::getBrief, ordersHistory.getBrief());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
    }

    @Override
    public void passOrder(Orders orders) {
        Long id = orders.getId();
        Integer status = orders.getStatus();
        if(status == 3){
            orders.setGeneralManager1(orders.getUser());
            orders.setGeneralManager1Op("审批意见: 同意");
            orders.setStatusInfo("等待最终审批");
        }if(status == 4){
            orders.setGeneralManager2(orders.getUser());
            orders.setGeneralManager2Op("审批意见: 同意");
            orders.setStatusInfo("审批通过, 等待厂长填写单据");
        }
        orders.setStatus(status+1).setUpdater(null).setUpdateDate(null);
        ordersMapper.updateById(orders);
        //历史
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getDesigner());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("订单审批意见：通过");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(id);
        ordersHistory.setOperate(1);
        ordersHistoryMapper.insert(ordersHistory);
    }

    @Override
    public void equipmentConfirm(Orders orders) {
        Long id = orders.getId();
        //订单
        orders.setUpdateDate(null);
        ordersMapper.updateById(orders);
        //历史
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getDesigner());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("安装单内容修改");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(id);
        ordersHistory.setOperate(1);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,id)
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate())
                .eq(OrdersHistory::getBrief, ordersHistory.getBrief());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
    }

    @Override
    public void shipmentConfirm(Orders orders) {
        Long id = orders.getId();
        OrdersHistory ordersHistory = new OrdersHistory();
        SysUser sysUser = sysUserMapper.selectById(orders.getDesigner());
        String name = sysDeptMapper.selectById(sysUser.getDeptId()).getName();
        ordersHistory.setBrief("安装单内容修改");
        ordersHistory.setOperator(sysUser.getRealName()+"("+name+")");
        ordersHistory.setOrderId(id);
        ordersHistory.setOperate(1);
        LambdaQueryWrapper<OrdersHistory> ordersHistoryLambdaQueryWrapper = new LambdaQueryWrapper<OrdersHistory>();
        ordersHistoryLambdaQueryWrapper.eq(OrdersHistory::getOrderId,id)
                .eq(OrdersHistory::getOperate, ordersHistory.getOperate())
                .eq(OrdersHistory::getBrief, ordersHistory.getBrief());
        OrdersHistory ordersHistory1 = ordersHistoryMapper.selectOne(ordersHistoryLambdaQueryWrapper);
        if(ordersHistory1 == null){
            ordersHistoryMapper.insert(ordersHistory);
        }else {
            ordersHistoryMapper.update(ordersHistory,ordersHistoryLambdaQueryWrapper);
        }
    }
}
